package com.tdx.blog_nowcoder.service;

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.tdx.blog_nowcoder.dao.DiscussPortMapper;
import com.tdx.blog_nowcoder.entity.DiscussPort;
import com.tdx.blog_nowcoder.utils.SensitiveFilter;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class DiscussPortService {

    private static final Logger logger = LoggerFactory.getLogger(DiscussPortService.class);
    @Autowired
    private DiscussPortMapper discussPortMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Value("${caffeine.posts.max-size}")
    private int max_size;

    @Value("${caffeine.posts.expire-seconds}")
    private int expireSeconds;

    //     // 帖子列表缓存
    private LoadingCache<String,List<DiscussPort>> DiscussPortLoadingCache;

    //  // 帖子总数缓存
    private LoadingCache<Integer,Integer> postRowsLoadingCache;

    @PostConstruct
    public void init(){
        DiscussPortLoadingCache = Caffeine.newBuilder()
                .maximumSize(max_size)
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                .build(new CacheLoader<String, List<DiscussPort>>() {
                    @Override
                    public @Nullable List<DiscussPort> load(@NonNull String key) throws Exception {
                        if (key == null || key.length() == 0) {
                            throw new IllegalArgumentException("参数错误!");
                        }
                        String[] params = key.split(":");
                        if (params == null || params.length != 2) {
                            throw new IllegalArgumentException("参数错误!");
                        }
                        int offset = Integer.valueOf(params[0]);
                        int limit = Integer.valueOf(params[1]);
                        // 二级缓存: Redis -> mysql

                        logger.debug("load post list from DB.");
                        return discussPortMapper.selectDiscussPosts(0, offset, limit, 1);
                    }
                });


        postRowsLoadingCache = Caffeine.newBuilder()
                .maximumSize(max_size)
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                .build(new CacheLoader<Integer, Integer>() {
                    @Override
                    public @Nullable Integer load(@NonNull Integer key) throws Exception {
                        logger.debug("load post rows from DB.");
                        return discussPortMapper.getItemRows(key);
                    }
                });
    }



    public List<DiscussPort> selectDiscussPosts(int userId, int offset, int limit,int orderMode){
        if (userId == 0 && orderMode == 1) {
            return DiscussPortLoadingCache.get(offset + ":" + limit);
        }

        logger.debug("load post list from DB.");
        return discussPortMapper.selectDiscussPosts(userId, offset, limit, orderMode);

//        return discussPortMapper.selectDiscussPosts(userId,offset,limit,orderMode);
    }

    public int getTotalRows(int userId){
        if (userId == 0) {
            return postRowsLoadingCache.get(userId);
        }

        logger.debug("load post rows from DB.");

        return discussPortMapper.getItemRows(userId);
    }

    public int addDiscussPort(DiscussPort post){
        if (post == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }

        // 转义HTML标记
        post.setTitle(HtmlUtils.htmlEscape(post.getTitle()));
        post.setContent(HtmlUtils.htmlEscape(post.getContent()));
        // 过滤敏感词
        post.setTitle(sensitiveFilter.filter(post.getTitle()));
        post.setContent(sensitiveFilter.filter(post.getContent()));

        return discussPortMapper.insertDiscussPort(post);
    }

    public DiscussPort getDiscussPostsById(int discussPostId){

        return discussPortMapper.getDiscussPostsById(discussPostId);
    }

    public int updateCommentCount(int id,int count){
        return discussPortMapper.updateCommentCount(id,count);
    }

    //置顶
    public int updateType(int postId,int type){
        return discussPortMapper.updateType(postId,type);
    }

    //加精
    public int updateStatus(int postId,int status){
        return discussPortMapper.updateStatus(postId,status);
    }

    public int updateScore(int postId,double score){
        return discussPortMapper.updateScore(postId,score);
    }






}
